package com.ruoyi.iot.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.mongo.domain.Record;
import com.ruoyi.common.mongo.service.IRecordService;
import com.ruoyi.iot.domain.mqtt.DepthMqttMessage;
import com.ruoyi.iot.domain.mqtt.constants.DepthMqttMethod;
import com.ruoyi.iot.service.IDepthMqttMessageService;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 图深回复客户端
 * @Author: 陈江灿
 * @CreateTime: 2025-02-14
 */
@Service
@Slf4j
public class DepthMqttMessageServiceImpl implements IDepthMqttMessageService {

    @Autowired
    private IRecordService recordService;

    @Autowired
    private MqttClientTemplate client;

    /**
     * 处理mqtt消息
     * @param mqttMessage mqtt 实体参数
     * @param topic       订阅的主题
     */
    @Override
    public void handle(DepthMqttMessage mqttMessage, String topic) {
        String cmd = mqttMessage.getCmd();
        log.info("收到图深设备消息：{}", cmd);
        switch (cmd) {
            case DepthMqttMethod.GET_DEV_BASE_CONF:
                // 获取设备基本信息
                break;
            case DepthMqttMethod.SET_DEV_BASE_CONF:
                // 设置设备基本信息
                break;
            case DepthMqttMethod.ADD_USER:
                // 添加更新人员信息
                break;
            case DepthMqttMethod.GET_USER_INFO:
                //查询人员信息
                break;
            case DepthMqttMethod.DEL_USER:
                // 删除人员信息
                break;
            case DepthMqttMethod.REPORT_VISIT_RECORD:
                // 识别信息自动推送
                reportVisitRecord(mqttMessage, topic);
                break;
            case DepthMqttMethod.REBOOT:
                // 重启设备信息
                break;
            case DepthMqttMethod.RESTORE:
                // 恢复出厂设置信息
                break;
            case DepthMqttMethod.POWER_OFF:
                // 恢复出厂设置信息
                break;
            case DepthMqttMethod.GET_DEV_FACE_PARAM_CONF:
                // 获取人脸机参数
                break;
            case DepthMqttMethod.SET_DEV_FACE_PARAM_CONF:
                // 设置人脸机参数
                break;
            case DepthMqttMethod.GET_USER_VISIT_RECORD:
                //查询人员考勤记录
                break;
            default:
                log.error("未找到对应的方法");
                break;
        }
    }

    /**
     * 设备向服务器推送人员考勤信息
     * @param mqttMessage
     * @param topic
     */
    private void reportVisitRecord(DepthMqttMessage mqttMessage, String topic) {
        String param = String.valueOf(mqttMessage.getParam());
        JSONObject jsonObject = JSON.parseObject(param);
        if (ObjectUtil.isNotNull(jsonObject)) {
            Record record = new Record();
            record.setName(jsonObject.getString("UserName"));
            record.setImgData(jsonObject.getString("FaceImgBase64"));
            record.setSn(mqttMessage.getDevID());
            record.setCreatedAt(jsonObject.getLong("TimeStamp"));
            record.setPersonId(jsonObject.getString("CustomID"));
            record.setRecordId(mqttMessage.getMsgId());
            record.setType("0");
            List<Record> list = recordService.lambdaQuery().eq(Record::getSn, mqttMessage.getDevID())
                    .eq(Record::getCreatedAt, jsonObject.getLong("TimeStamp")).list();
            if(isEmpty(list)){
                recordService.save(record);
                // 回复mqtt消息
                DepthMqttMessage message = new DepthMqttMessage();
                message.setMsgId(UUID.randomUUID().toString());
                message.setCmd(DepthMqttMethod.REPORT_VISIT_RECORD);
                message.setDevID(mqttMessage.getDevID());
                message.setMsg("ok");
                message.setCode("0");
                String topicDownstream = "device/Uface/" + mqttMessage.getDevID() + "/Downstream";
                client.publish(topicDownstream, JSONObject.toJSONString(message).getBytes(StandardCharsets.UTF_8));
            }
        }

    }

    /**
     * 判空
     */
    public static <T> boolean isEmpty(List<T> list) {
        return Optional.ofNullable(list).map(List::isEmpty).orElse(true);
    }
}
